package com.alm.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ywy
 * @date 2024/8/6
 * 获取系统mac地址 工具类
 */
public class ComputerUniqueIdUtil {
    /**
     * Windows
     */
    public static final String WINDOWS = "windows";
    /**
     * Linux
     */
    public static final String LINUX = "linux";
    /**
     * Unix
     */
    public static final String UNIX = "unix";
    /**
     * 正则表达式
     */
    public static final String REGEX = "\\b\\w+:\\w+:\\w+:\\w+:\\w+:\\w+\\b";

    /**
     * 获取当前计算机操作系统名称 例如:windows,Linux,Unix等.
     *
     * @return String - 计算机操作系统名称
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/10/10 17:15
     */
    public static String getOSName() {
        return System.getProperty("os.name").toLowerCase();
    }

    /**
     * 获取当前计算机操作系统名称前缀 例如:windows,Linux,Unix等.
     *
     * @return String - 计算机操作系统名称
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/10/10 17:15
     */
    public static String getOSNamePrefix() {
        String name = getOSName();
        if (name.startsWith(WINDOWS)) {
            return WINDOWS;
        } else if (name.startsWith(LINUX)) {
            return LINUX;
        } else if (name.startsWith(UNIX)) {
            return UNIX;
        } else {
            return "";
        }
    }

    /**
     * 从字节获取 MAC
     *
     * @param bytes - 字节
     * @return String - MAC
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/10/12 8:55
     */
    private static String getMacFromBytes(byte[] bytes) {
        StringBuffer mac = new StringBuffer();
        byte currentByte;
        boolean first = false;
        for (byte b : bytes) {
            if (first) {
                mac.append("-");
            }
            currentByte = (byte) ((b & 240) >> 4);
            mac.append(Integer.toHexString(currentByte));
            currentByte = (byte) (b & 15);
            mac.append(Integer.toHexString(currentByte));
            first = true;
        }
        return mac.toString().toUpperCase();
    }

    /**
     * 获取 Windows 网卡的 MAC 地址
     *
     * @return String - MAC 地址
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/10/10 17:15
     */
    private static String getWindowsMACAddress() {
        InetAddress ip = null;
        NetworkInterface ni = null;
        List<String> macList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
                    .getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                ni = (NetworkInterface) netInterfaces.nextElement();
                //  遍历所有 IP 特定情况，可以考虑用 ni.getName() 判断
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = (InetAddress) ips.nextElement();
                    // 非127.0.0.1
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
                        macList.add(getMacFromBytes(ni.getHardwareAddress()));
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("获取 Windows MAC 错误" + e.getMessage());
        }
        if (macList.size() > 0) {
            return macList.get(0);
        } else {
            return "";
        }
    }

    /**
     * 获取 Linux 网卡的 MAC 地址 （如果 Linux 下有 eth0 这个网卡）
     *
     * @return String - MAC 地址
     */
    private static String getLinuxMACAddressForEth0() {
        String mac = null;
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            // Linux下的命令，一般取eth0作为本地主网卡
            process = Runtime.getRuntime().exec("ifconfig eth0");
            // 显示信息中包含有 MAC 地址信息
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            int index = -1;
            while ((line = bufferedReader.readLine()) != null) {
                // 寻找标示字符串[hwaddr]
                index = line.toLowerCase().indexOf("hwaddr");
                if (index >= 0) {
                    // // 找到并取出 MAC 地址并去除2边空格
                    mac = line.substring(index + "hwaddr".length() + 1).trim();
                    break;
                }
            }
        } catch (IOException e) {
            System.out.println("获取 Linux MAC 信息错误" + e.getMessage());
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                System.out.println("获取 Linux MAC 信息错误" + e1.getMessage());
            }
            bufferedReader = null;
            process = null;
        }
        return mac;
    }

    /**
     * 获取 Linux 网卡的 MAC 地址
     *
     * @return String - MAC 地址
     */
    private static String getLinuxMACAddress() {
        String mac = null;
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            // Linux下的命令 显示或设置网络设备
            process = Runtime.getRuntime().exec("ifconfig");
            // 显示信息中包含有 MAC 地址信息
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            int index = -1;
            while ((line = bufferedReader.readLine()) != null) {
                Pattern pat = Pattern.compile(REGEX);
                Matcher mat = pat.matcher(line);
                if (mat.find()) {
                    mac = mat.group(0);
                }
            }
        } catch (IOException e) {
            System.out.println("获取 Linux MAC 信息错误" + e.getMessage());
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                System.out.println("获取 Linux MAC 信息错误" + e1.getMessage());
            }
            bufferedReader = null;
            process = null;
        }
        return mac;
    }

    /**
     * 获取当前计算机网卡的 MAC 地址
     *
     * @return String - 网卡的 MAC 地址
     */
    public static String getMACAddress() {
        switch (getOSNamePrefix()) {
            case WINDOWS:
                return getWindowsMACAddress();
            case LINUX:
                String macAddressForEth0 = getLinuxMACAddressForEth0();
                if (StringUtils.isBlank(macAddressForEth0)) {
                    macAddressForEth0 = getLinuxMACAddress();
                }
                return macAddressForEth0;
            default:
                return "";
        }
    }

}

